package com.daxt.controller.filemanager;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.common.annotations.OperLog;
import com.daxt.common.result.*;
import com.daxt.common.util.DateUtil;
import com.daxt.mapper.archives.ArchivesDocFileMapper;
import com.daxt.mapper.sys.ArchivesClassMapper;
import com.daxt.model.constant.BaseConstants;
import com.daxt.model.dic.*;
import com.daxt.model.dto.BaseQueryDto;
import com.daxt.model.service.archives.vo.*;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.service.*;
import com.daxt.utils.ArchivesUtil;
import com.daxt.utils.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.mapper.archives.ArchivesDocValueMapper;
import com.daxt.mapper.archives.ArchivesTypeDocMapper;
import com.daxt.mapper.sys.ArchivesFondsMapper;
import com.daxt.mapper.sys.ArchivesTypeMapper;
import com.daxt.model.service.archives.result.ArchivesCols;
import com.daxt.model.service.archives.result.ArchivesDetails;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "案卷整理")
@RestController
@RequestMapping("/fileManager")
public class DossierController {

    @Autowired
    private ArchivesDocMapper archivesDocMapper;
    @Autowired
    private ArchivesDocValueMapper archivesDocValueMapper;
    @Autowired
    private ArchivesTypeMapper archivesTypeMapper;
    @Autowired
    private ArchivesTypeDocMapper archivesTypeDocMapper;
    @Autowired
    private ArchivesFondsMapper archivesFondsMapper;
    @Autowired
    private DossierService dossierService;
    @Autowired
    private DocService docService;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private FondsListService fondsListService;
    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private ArchivesDocFileMapper archivesDocFileMapper;
    @Autowired
    private ArchivesClassMapper archivesClassMapper;
    @Autowired
    private ArchivesBehaveLogService archivesBehaveLogService;

//    @ApiOperation(value = "获取列表", notes = "")
//    @GetMapping("/dossier")
//    public Result<ArchivesList> list(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
//                                     @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
//                                     @ApiParam("") @RequestParam(value = "extType", required = false) String extType,
//                                     @ApiParam("") @RequestParam(value = "fondsNum", required = false) String fondsNum,
//                                     @ApiParam("") @RequestParam(value = "classNum", required = false) String classNum,
//                                     @ApiParam("条件") @RequestParam(value = "condition", required = false) String condition,
//                                     @ApiParam("关键词") @RequestParam(value = "keywords", required = false) String keywords,
//                                     @ApiParam("部门") @RequestParam(value = "deptId", required = false) String deptId) {
//        return docService.list(pageNum, pageSize, extType, fondsNum, "0", condition, classNum, keywords, "dossier", deptId, "0", "0", null);
//    }

    @ApiOperation(value = "案卷详情", notes = "")
    @GetMapping("/dossier/{id}")
    public Result<ArchivesDetails> details(@PathVariable("id") String id) {
        ArchivesDoc archivesDossier = archivesDocMapper.selectById(id);
        if (archivesDossier == null) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "案卷信息查找不到", null);
        }
        return docService.details(archivesDossier);
    }

    @ApiOperation(value = "添加案件（散文件移动到卷内）", notes = "")
    @PostMapping("/dossier/{id}")
    @Transactional(rollbackFor = Exception.class)
    @OperLog(operModul = "散文件移动到卷内文件", operType = "MOVE", operDesc = "新日志")
    @LoginAuth()
    public Result<String> addDoc(@ApiIgnore @LoginUser UserInfo loginUser,@PathVariable("id") String id, @RequestBody List<String> ids,
                                 HttpServletRequest request) {
        if (StringUtils.isEmpty(id) || (ids == null || ids.size() == 0)) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "参数异常", null);
        }
//		String createFileNum = RedisUtil.getSysConfig(SystemConfigType.ITEM_NUM_LENGTH);
//		if(StringUtils.isEmpty(createFileNum))return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "缺少系统配置key：ITEM_NUM_LENGTH",null);
        ArchivesDoc selectById = archivesDocMapper.selectById(id);
        Map<String, String> itemNumMap = new HashMap();
        //校验件号是否重复
        Set<String> hashSet = new HashSet<String>();
        for (String string : ids) {
            ArchivesDoc itemBean = archivesDocMapper.selectById(string);
            itemBean.setDossierId(Long.parseLong(id));
            itemBean.setFileType(DicDocFileType.DOC.getKey());


            if (StringUtils.isEmpty(itemBean.getItemNum()))
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "件号不能为空！", null);
            if (!archivesService.verifyDocNum(itemBean))
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "存在重复的件号：" + itemBean.getItemNum(), null);

            if (!hashSet.add(itemBean.getItemNum()))
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "添加的数据存在重复的件号：" + itemBean.getItemNum(), null);

            itemNumMap.put(string, itemBean.getItemNum());
        }

        try {

            for (String string : ids) {
                ArchivesDoc docEntity1 = new ArchivesDoc();
                docEntity1.setId(Long.parseLong(string));
                docEntity1.setItemNum(itemNumMap.get(string));
                docEntity1.setArchivalNum(selectById.getArchivalNum());
                docEntity1.setCategoryNum(selectById.getCategoryNum());
                docEntity1.setArchivalYear(selectById.getArchivalYear());
                docEntity1.setFondsName(selectById.getFondsName());
                docEntity1.setDeptId(selectById.getDeptId());
                docEntity1.setClassId(selectById.getClassId());
//                docEntity1.setClassNum(selectById.getClassNum());
                docEntity1.setDossierNum(selectById.getDossierNum());
                docEntity1.setDossierId(Long.parseLong(id));
                docEntity1.setFileType("doc");

                archivesDocMapper.updateById(docEntity1);
            }


        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("添加失败");
        }
        operationLogService.saveLog("2", "添加" + ids.toArray() + "件到" + id + "卷中成功", request);
        archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(BaseUtil.listToString(ids), BehaveLogType.ADD_ARCHIVIST_INNER.getKey(),BehaveLogType.ADD_ARCHIVIST_INNER.getValue(),"添加到案卷“"+selectById.getTitle()+"”中；"),loginUser ,request);

        return ResultUtil.success();
    }

    @ApiOperation(value = "获取字段", notes = "")
    @GetMapping("/dossier/cols")
    public Result<ArchivesCols> getCols(@ApiParam("") @RequestParam(value = "typeId", required = false) String typeId,
                                        @ApiParam("") @RequestParam(value = "fondsId", required = false) String fondsId,
                                        @RequestParam(value = "colType", required = false) String colType) {
        ArchivesCols archivesCols = new ArchivesCols();

        //获取门类
        ArchivesType typeBean = archivesTypeMapper.selectById(typeId);
        if (typeBean != null ) {
            QueryWrapper<ArchivesTypeDoc> col = new QueryWrapper<>();
            col.eq("extType", "dossier");
            // col.eq("isEdit", "1");
            col.eq("typeId", typeBean.getId());
            if ("insert".equals(colType)) {
                col.eq("isInsert", "1");
            } else if ("edit".equals(colType)) {
                col.eq("isEdit", "1");
            } else if ("list".equals(colType)) {
                col.eq("isList", "1");
            } else if ("import".equals(colType)) {
                col.eq("isImport", "1");
            } else if ("export".equals(colType)) {
                col.eq("isExport", "1");
            } else if ("isBathEdit".equals(colType)) {
                col.eq("isBathEdit", "1");
            }
            List<ArchivesTypeDoc> baseCols = archivesTypeDocMapper.selectList(col);
            archivesCols.setDossierBaseList(baseCols);
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", archivesCols);
    }

    @ApiOperation(value = "保存", notes = "")
    @PostMapping("/dossier")
    @OperLog(operModul = "添加案卷", operType = "ADD", operDesc = "新日志功能")
    @Transactional(rollbackFor = Exception.class)
    @LoginAuth()
    public Result<String> dossierSave(@ApiIgnore @LoginUser UserInfo loginUser, @RequestBody ArchivesDoc archivesDossier
                                     ,HttpServletRequest request) {
        System.out.println("============================"+archivesDossier.getArchivalNum());
        System.out.println(archivesDossier.getClassName());
        ArchivesFonds afBean = archivesFondsMapper.selectById(archivesDossier.getFondsId());
        String fondsName = afBean.getFondsName();
        archivesDossier.setFondsName(fondsName);

        //校验案卷号是否重复
        if (!archivesService.verifyDossierNum(archivesDossier))return ResultUtil.error("案卷号重复！！！");

//        //解析分类树
//        archivesService.parseClassNum(archivesDossier);

        //获取门类
        ArchivesType typeBean = archivesTypeMapper.selectById(archivesDossier.getTypeId());


        if (null == typeBean) return ResultUtil.error("门类不正确！！！");
        //修改 档案号可以自行输入 lig 2021-06-10
        if(!StringUtils.isEmpty(archivesDossier.getFondsId())){
            ArchivesFonds archivesFonds = archivesFondsMapper.selectById(archivesDossier.getFondsId());
            archivesDossier.setFondsNum(archivesFonds.getFondsNum());
        }
        Result<String> r = archivesService.buildArchivalNum(archivesDossier, typeBean, true);
        if (r.getCode().equals(ResultCode.RESULT_ERROR.getCode())) return r;

        archivesDossier.setCreateTime(LocalDateTime.now());
        archivesDossier.setDocFrom("1");

        //将保管期限初始化为0，具体原因不知道
        ArchivesDoc.initData(archivesDossier);

        Result<String> dossierSave = dossierService.dossierSave(archivesDossier);

        if(dossierSave.getCode().equals(ResultCode.RESULT_SUCCESS.getCode())){
            archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(archivesDossier.getId().toString(),BehaveLogType.ADD.getKey(),BehaveLogType.ADD.getValue(),"创建案卷"),loginUser ,request);
        }

        return dossierSave;
    }

    @ApiOperation(value = "修改", notes = "")
    @PutMapping("/dossier")
    @OperLog(operModul = "编辑案卷", operType = "EDIT", operDesc = "")
    @Transactional(rollbackFor = Exception.class)
    @LoginAuth()

    public Result<String> dossierEdit(@ApiIgnore @LoginUser UserInfo loginUser,@RequestBody ArchivesDoc archivesDossier,
                                      HttpServletRequest request) {

        ArchivesDoc dossOld=archivesDocMapper.selectById(archivesDossier.getId());

        //校验案卷号是否重复
        if (!archivesService.verifyDossierNum(archivesDossier))
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "案卷号重复！！！", null);

        //获取门类
        ArchivesType typeBean = archivesTypeMapper.selectById(archivesDossier.getTypeId());

        if (null != typeBean) {
            //修改 档案号可以自行输入 lig 2021-06-10
            if(!StringUtils.isEmpty(archivesDossier.getFondsId())){
                ArchivesFonds archivesFonds = archivesFondsMapper.selectById(archivesDossier.getFondsId());
                archivesDossier.setFondsNum(archivesFonds.getFondsNum());
            }
            Result<String> r = archivesService.buildArchivalNum(archivesDossier, typeBean, true);
            if (r.getCode().equals(ResultCode.RESULT_ERROR.getCode())) return r;

        } else {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "门类不正确！！！", null);
        }

//        //解析分类树
//        archivesService.parseClassNum(archivesDossier);

        Result<String> dossierEdit =dossierService.dossierEdit(archivesDossier);

        Map<String,String> typeDocMap=archivesService.gainMetadataEditField(dossOld.getTypeId(),dossOld.getFileType());
        if(dossierEdit.getCode().equals(ResultCode.RESULT_SUCCESS.getCode()) && !typeDocMap.isEmpty()){
            String description = ArchivesUtil.compareArchives(dossOld,archivesDossier,typeDocMap);
            archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(archivesDossier.getId().toString(),BehaveLogType.UPDATE.getKey(),BehaveLogType.UPDATE.getValue(),description),loginUser ,request);
        }

        return dossierEdit;
    }

    @ApiOperation(value = "删除", notes = "")
    @DeleteMapping("/dossier")
    @OperLog(operModul = "删除案卷/件", operType = "DELETE", operDesc = "新日志")
    public Result<String> dossierDel(@RequestBody List<Long> ids) {
        try {
            archivesDocMapper.deleteBatchIds(ids);
            QueryWrapper<ArchivesDocValue> wrapper = new QueryWrapper<>();
            wrapper.in("docId", ids);
            archivesDocValueMapper.delete(wrapper);
            QueryWrapper<ArchivesDoc> queryWrapper = new QueryWrapper<ArchivesDoc>();
            queryWrapper.in("dossierId", ids);
            queryWrapper.select("id");
            List<ArchivesDoc> docList = archivesDocMapper.selectList(queryWrapper);
            if (docList != null && docList.size() > 0) {
                List<Long> docIds = new ArrayList<Long>();
                for (ArchivesDoc archivesDoc : docList) {
                    docIds.add(archivesDoc.getId());
                }
                QueryWrapper<ArchivesDoc> wrapperDoc = new QueryWrapper<>();
                wrapperDoc.in("dossierId", docIds);
                archivesDocMapper.delete(wrapperDoc);
                QueryWrapper<ArchivesDocValue> wrapperDel = new QueryWrapper<ArchivesDocValue>();
                wrapperDel.in("docId", docIds);
                archivesDocValueMapper.delete(wrapperDel);
            }
            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "删除失败", null);
        }
    }

    @ApiOperation(value = "案卷归档审批", notes = "")
    @PostMapping("/dossier/file")
    @Transactional(rollbackFor = Exception.class)
    @OperLog(operModul = "案卷归档审批", operType = "UPDATE", operDesc = "新日志")
    @LoginAuth()
    public Result<String> dossierEdit(@ApiIgnore @LoginUser UserInfo loginUser,@ApiParam("全宗ID") @RequestParam(value = "fondsId") String fondsId
            , @ApiParam("门类ID") @RequestParam(value = "typeId") String typeId
            , @ApiParam("分类Id") @RequestParam(value = "classId") String classId
            , @ApiParam("state") @RequestParam(value = "state",required = false ) String state
            , @RequestBody List<String> ids
            ,HttpServletRequest request) {


        try {
            Set<String> hashSet = new HashSet<String>();
            for (String id : ids) {
                //校验是否已经有归档数据
                ArchivesDoc aDoc = archivesDocMapper.selectById(id);
                System.out.println("aDoc.getArchivalNum()"+aDoc.getArchivalNum());
                if (!StringUtils.isEmpty(aDoc.getDossierNum())) {
                    StringBuffer existData = new StringBuffer().append(aDoc.getFondsId())
                            .append("-").append(aDoc.getTypeId()).append("-").append(aDoc.getClassId()).append("-").append(aDoc.getDossierNum());
//                    archivesService.verifyDossierNum()
                    if (archivesService.existArchive(aDoc)) {
                        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "数据已经归档或审批中(全宗ID - 门类ID - 类目ID - 卷号 )：" + existData.toString(), null);
                    }
                    if (!hashSet.add(existData.toString())) {
                        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作存在重复数据(全宗号ID - 门类ID - 类目ID - 卷号 )：" + existData.toString(), null);
                    }
                }

            }

            ArchivesType at = null;
            if (!StringUtils.isEmpty(typeId)) {
                at = archivesTypeMapper.selectById(Long.parseLong(typeId));
                if (null == at) return ResultUtil.error( "门类不正确");
            }
            //自动生成卷号和件号
            if(StringUtils.isEmpty(classId)){
                QueryWrapper<ArchivesDoc> wrapper = new QueryWrapper<ArchivesDoc>();
                wrapper.select("distinct classId");
                wrapper.eq("typeId",typeId);
                wrapper.eq("fondsId",fondsId);
                wrapper.in("id",ids);
                List<ArchivesDoc> classIds= archivesDocMapper.selectList(wrapper);//获取ids下包含的classId
                Map<String,List<String>> map=new HashMap<>();
                for (int i=0;i<classIds.size();i++){
                    if(classIds.get(i)==null){
                        continue;
                    }
                    String cId=classIds.get(i).getClassId().toString();
                    wrapper = new QueryWrapper<ArchivesDoc>();
                    wrapper.select("id");
                    wrapper.eq("typeId",typeId);
                    wrapper.eq("fondsId",fondsId);
                    wrapper.eq("classId",cId);
                    wrapper.in("id",ids);
                    List<ArchivesDoc> docListId= archivesDocMapper.selectList(wrapper);//获取对应classId的docId集合
                    List<String> listId=new ArrayList<>();
                    for(int j=0;j<docListId.size();j++){
                        String id=docListId.get(j).getId().toString();
                        listId.add(id);
                    }
                    map.put(cId,listId);
                }
                //遍历集合对与classId对应的ids进行件号卷号的生成
                if(map.isEmpty()){

                    Result str= archivesService.automationDossierItemNumNum(at,"dossier",null,fondsId,ids);
                    if("1001".equals(str.getCode())){
                        return str;
                    }
                }else{
                    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                        Result str= archivesService.automationDossierItemNumNum(at,"dossier",entry.getKey(),fondsId,entry.getValue());
                        if("1001".equals(str.getCode())){
                            return str;
                        }
                    }
                }

            }else{
                Result str= archivesService.automationDossierItemNumNum(at,"dossier",classId,fondsId,ids);
                if("1001".equals(str.getCode())){
                    return str;
                }
            }



            ArchivesDoc entity = new ArchivesDoc();
            //if (!StringUtils.isEmpty(state) && "6".equals(state)){
            //    entity.setState(DicDocState.neaten.getKey());
            //}else {
                entity.setState(DicDocState.approval.getKey());
            //}

            if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
                entity.setGroupBy(loginUser.getRealName());//组卷人
                entity.setGroupTime(DateUtil.getCurrentTime());//组卷时间
            }
            System.out.println("aDoc.getArchivalNum()"+entity.getArchivalNum());

            QueryWrapper<ArchivesDoc> updateWrapperDossier = new QueryWrapper<>();
            updateWrapperDossier.in("id", ids);
            updateWrapperDossier.or().in("dossierId", ids);

            int rows=archivesDocMapper.update(entity, updateWrapperDossier);

            if(rows>0){
                archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(BaseUtil.listToString(ids),BehaveLogType.ARCHIVIST.getKey(),BehaveLogType.ARCHIVIST.getValue(),"从档案收集归档到档案整理"),loginUser , request );
            }

            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", null);
        }
    }


    @ApiOperation(value = "获取列表(附件)（内蒙版）", notes = "")
    @GetMapping("/accessoryList")
    public Result<PageInfo<ArchivesDocFile>> accessoryList(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                                           @ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                                           @ApiParam("全宗ID") @RequestParam(value = "fondsId", required = false) String fondsId,
                                                           @ApiParam("门类ID") @RequestParam(value = "typeId", required = false) String typeId,
                                                           @ApiParam("分类ID") @RequestParam(value = "classId", required = false) String classId,
                                                           @ApiParam("年度") @RequestParam(value = "year", required = false) String year,
//									 @ApiParam("dossierId   0文件  dossierId卷下的件列表 ") @RequestParam(value = "dossierId", required = false) String dossierId,
//									 @ApiParam("卷dossier 件doc  scattered 散文件") @RequestParam(value = "fileType", required = false) String fileType,
                                                           @ApiParam("0 整理 1归档审批 2归档 3 鉴定 4销毁 5回收站") @RequestParam(value = "state", required = false) String state) {


        QueryWrapper<ArchivesDoc> queryWrapper = new QueryWrapper<ArchivesDoc>();
        queryWrapper.eq(BaseConstants.field_fondsId, fondsId);
        queryWrapper.eq(BaseConstants.field_typeId, typeId);
        queryWrapper.eq(BaseConstants.field_classId, classId);
        queryWrapper.eq("archivalYear", year);
        queryWrapper.eq(BaseConstants.field_state, state);
        queryWrapper.eq(BaseConstants.field_isDelete, BaseConstants.DELETE_NORMAL);
        List<ArchivesDoc> infos = archivesDocMapper.selectList(queryWrapper);
        List<Long> adfIds = new ArrayList<Long>();
        for (ArchivesDoc aDoc : infos) {
            adfIds.add(aDoc.getId());
        }

        if (!BaseUtil.listIsNotNullElement(adfIds)) {
            PageInfo<ArchivesDocFile> nullR = new PageInfo<ArchivesDocFile>();
            nullR.setPages(1l);
            nullR.setPageNum(0l);
            nullR.setTotal(0l);
            nullR.setList(new ArrayList<ArchivesDocFile>());
            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", nullR);
        }


        Page<ArchivesDocFile> page = new Page<ArchivesDocFile>(pageNum == null ? 0 : pageNum,
                pageSize == null ? 10 : pageSize);
        QueryWrapper<ArchivesDocFile> qw = new QueryWrapper<ArchivesDocFile>();
        qw.in("docId", adfIds);

        IPage<ArchivesDocFile> info = archivesDocFileMapper.selectPage(page, qw);
        List<ArchivesDocFile> list = new ArrayList<ArchivesDocFile>();
        info.getRecords().forEach((ArchivesDocFile adFile) -> {
            adFile.setFileUrl(adFile.getFileUrl());
        });

        PageInfo<ArchivesDocFile> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(),
                info.getRecords());

        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", data);
    }


    @ApiOperation(value = "案卷/件，移动目录树", notes = "")
    @PutMapping("/dossierOrDoc/move")
    @Transactional(rollbackFor = Exception.class)
    @OperLog(operModul = "案卷/件，移动目录树", operType = "UPDATE", operDesc = "新日志")
    @LoginAuth()
    public Result<String> move(
            @ApiIgnore @LoginUser UserInfo loginUser,
            @ApiParam("全宗ID") @RequestParam(value = "fondsId", required = true) String fondsId,
            @ApiParam("门类ID") @RequestParam(value = "typeId", required = true) String typeId,
            @ApiParam("0代表案件  1代表案卷") @RequestParam(value = "model", required = true) String model,
            @ApiParam("doc代表案件  dossier代表案卷") @RequestParam(value = "fileType", required = true) String fileType,
            @ApiParam("分类ID") @RequestParam(value = "classId", required = false) String classId,
            @RequestBody List<String> ids,
            HttpServletRequest request) {

        ArchivesDoc entity = new ArchivesDoc();

        StringBuilder description = new StringBuilder();

        if (!StringUtils.isEmpty(fondsId)) {
//            QueryWrapper<ArchivesFonds> queryWrapper = new QueryWrapper<ArchivesFonds>();
//            queryWrapper.eq("fondsId", fondsId);
//            ArchivesFonds af = archivesFondsMapper.selectOne(queryWrapper);
            ArchivesFonds af = archivesFondsMapper.selectById(fondsId);
            entity.setFondsId(af.getId().toString());
            entity.setFondsNum(af.getFondsNum());
            entity.setFondsName(af.getFondsName());
        }
        if (!StringUtils.isEmpty(typeId)) {

            ArchivesType at = archivesTypeMapper.selectById(typeId);
            entity.setTypeId(at.getId());
            entity.setTypeNum(at.getTypeNum());

            description.append("门类移动到“").append(at.getTypeName()).append("”；");

        }
//        if (!StringUtils.isEmpty(classId)) {
//            ArchivesClass ac = archivesClassMapper.selectById(classId);
//            entity.setClassId(ac.getId().toString());
//            entity.setTypeNum(ac.getTypeNum());
//            entity.setClassName(ac.getClassName());
//        }
        if(!StringUtils.isEmpty(classId)){
//            entity.setClassNum(classId);
            ArchivesClass newClass=archivesClassMapper.selectById(classId);

            entity.setClassId(Long.parseLong(classId));

            description.append("分类移动到“").append(newClass.getClassName()).append("”；");
        }

        //案件移动到散文件中
        if("doc".equals(fileType) && "1".equals(model)){
            entity.setFileType("scattered");
            description.append("案件移动到散文件中；");
        }
        //卷内文件和散文件移动到案件中
        if( ( "scattered".equals(fileType) || "dossier".equals(fileType) ) && "0".equals(model)){
            entity.setDossierId(0L);
            entity.setItemNum("");
            entity.setDossierNum(null);
            entity.setFileType("doc");

            if("dossier".equals(fileType)){
                description.append("卷内文件移动到案件中；");
            }else{
                description.append("散文件移动到案件中；");
            }
        }

        //卷内文件移动到其它案卷的散文件中
        List<String> docIds=new ArrayList<>();
        if(( "scattered".equals(fileType) || "dossier".equals(fileType) )&& "1".equals(model)){
            List<ArchivesDoc> archivesDocList= archivesDocMapper.selectBatchIds(ids);
            for(int i=0;i<archivesDocList.size();i++){
                ArchivesDoc doc=archivesDocList.get(i);
                if(doc.getDossierId()!=0){
                    docIds.add(doc.getId().toString());

                };
            }
            ids.remove(docIds);
        }

        if(ids.size()>0){
            QueryWrapper<ArchivesDoc> updateWrapperDoc = new QueryWrapper<ArchivesDoc>();
            updateWrapperDoc.in("id", ids);
            archivesDocMapper.update(entity, updateWrapperDoc);
        }
        if(docIds.size()>0){
            entity.setDossierId(0L);
            entity.setFileType("scattered");
            QueryWrapper<ArchivesDoc> updateWrapperDoc = new QueryWrapper<ArchivesDoc>();
            updateWrapperDoc.in("id", docIds);
            entity.setItemNum("");
            entity.setDossierNum(null);
            archivesDocMapper.update(entity, updateWrapperDoc);
            description.append("卷内文件移动到散文件中；");
        }

        ArchivesBehaveLog behaveLog= new ArchivesBehaveLog(BaseUtil.listToString(ids),BehaveLogType.BATCH_MOVE.getKey(),BehaveLogType.BATCH_MOVE.getValue(),description.toString());
        archivesBehaveLogService.saveArchivesBehaveLog(behaveLog,loginUser ,request);

        return ResultUtil.success();
    }


    @ApiOperation(value = "案卷 - 打散", notes = "")
    @PutMapping("/dossier/scatter")
    @Transactional(rollbackFor = Exception.class)
    @OperLog(operModul = "案卷 - 打散", operType = "UPDATE", operDesc = "新日志")
    @LoginAuth()
    public Result<String> scatter(@ApiIgnore @LoginUser UserInfo loginUser,
                                  @RequestBody List<String> ids,
                                  HttpServletRequest request) {

        UpdateWrapper<ArchivesDoc> updateWrapperDoc = new UpdateWrapper<ArchivesDoc>();
        updateWrapperDoc.in("dossierId", ids);
        ArchivesDoc entity = new ArchivesDoc();
        entity.setFileType(DicDocFileType.SCATTERED.getKey());

        int i = archivesDocMapper.update(entity, updateWrapperDoc);
        if (i > 0) {
            if(!ids.isEmpty()){
                ArchivesBehaveLog archivesBehaveLog=new ArchivesBehaveLog(BaseUtil.listToString(ids),BehaveLogType.HIT_SCATTERED.getKey(),BehaveLogType.HIT_SCATTERED.getValue(),"将卷内文件打到散文件中；");
                archivesBehaveLogService.saveArchivesBehaveLog(archivesBehaveLog,loginUser ,request);
            }

            return ResultUtil.success();
        }

        return ResultUtil.error();

    }

    @ApiOperation(value = "案卷/件 - 批量修改", notes = "")
    @PutMapping("/dossierOrDoc/batchUpdate")
    @Transactional(rollbackFor = Exception.class)
    @OperLog(operModul = "案卷/件 - 批量修改", operType = "UPDATE", operDesc = "新日志")
    @LoginAuth()
    public Result<String> batchUpdate(
            @ApiIgnore @LoginUser UserInfo loginUser,
            @ApiParam("全宗ID") @RequestParam(value = "fondsId", required = false) String fondsId,
            @ApiParam("门类ID") @RequestParam(value = "typeId", required = false) String typeId,
            @ApiParam("分类ID") @RequestParam(value = "classId", required = false) String classId,
            @ApiParam("字段名") @RequestParam(value = "fieldName", required = true) String fieldName,
            @ApiParam("字段值") @RequestParam(value = "fieldValue", required = false) String fieldValue,
            @ApiParam("旧的字段内容") @RequestParam(value = "oldFieldValue", required = false) String oldFieldValue,
            @ApiParam("卷dossier 件doc  scattered 散文件") @RequestParam(value = "fileType", required = false) String fileType,
            @RequestBody(required = false) List<String> ids,
            HttpServletRequest request) {

        UpdateWrapper<ArchivesDoc> queryWrapperDoc = new UpdateWrapper<ArchivesDoc>();

        if (BaseUtil.listIsNotNullElement(ids)) queryWrapperDoc.in("id", ids);
        if (!StringUtils.isEmpty(fondsId)) queryWrapperDoc.eq(BaseConstants.field_fondsId, fondsId);
        if (!StringUtils.isEmpty(typeId)) queryWrapperDoc.eq(BaseConstants.field_typeId, typeId);
        if (!StringUtils.isEmpty(classId)) queryWrapperDoc.like(BaseConstants.field_classId, classId);
        if (!StringUtils.isEmpty(fileType)) queryWrapperDoc.eq("fileType", fileType);

        if(!StringUtils.isEmpty(oldFieldValue)){
            queryWrapperDoc.eq(fieldName, oldFieldValue);
        }

        ArchivesDoc entity = new ArchivesDoc();
        try {
            Field f = entity.getClass().getDeclaredField(fieldName);
            f.setAccessible(true);
            f.set(entity, BaseUtil.objectToString(fieldValue));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
            return ResultUtil.error();

        }

        int i = archivesDocMapper.update(entity, queryWrapperDoc);

        if(i>0){
            ArchivesTypeDoc typeDoc = archivesTypeDocMapper.selectOne(new QueryWrapper<ArchivesTypeDoc>().eq("typeId",typeId).eq("extType",fileType).eq("extColumn",fieldName));
            String columnComment=typeDoc.getColumnComment();
            if(!ids.isEmpty()){
                ArchivesBehaveLog archivesBehaveLog=new ArchivesBehaveLog(BaseUtil.listToString(ids),BehaveLogType.BATCH_UPDATE.getKey(),BehaveLogType.BATCH_UPDATE.getValue(),columnComment+"：从“"+oldFieldValue+"”修改为“"+fieldValue+"”；");
                archivesBehaveLogService.saveArchivesBehaveLog(archivesBehaveLog,loginUser ,request);
            }
        }



        return ResultUtil.success();


    }


    /*public static void main(String[] args) {
        String s = "fondsId:1";
        System.out.println(s.indexOf(":"));
    }*/
}
